package com.example.restclient.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.example.restclient.entity.Customer;

@RestController
public class CustomerController {

	@Autowired
	RestTemplate restTemplate;

	@RequestMapping(value = "/customer", method = RequestMethod.POST)
	public Customer addCusotmer(@RequestBody Customer customer) {
		return restTemplate.postForObject("http://localhost:8080/customer", customer, Customer.class);
	}

	@RequestMapping(value = "/customer", method = RequestMethod.GET)
	public List<Customer> getAllCustomers() {
		return restTemplate.getForObject("http://localhost:8080/customer",List.class);
	}

	@RequestMapping(value = "/customer/{id1}", method = RequestMethod.GET)
	public Customer getCustomer(@PathVariable(name = "id1") int id) {
		return restTemplate.getForObject("http://localhost:8080/customer/" + id, Customer.class);
	}

	@RequestMapping(value = "/customer/{id1}", method = RequestMethod.DELETE)
	public void deleteCustomer(@PathVariable(name = "id1") int id) {
		restTemplate.delete("http://localhost:8080/customer/" + id);
	}

	@RequestMapping(value = "/customer", method = RequestMethod.PUT)
	public Customer updateCustomer(@RequestBody Customer customer) {
		HttpEntity<Customer> httpEntity = new HttpEntity<Customer>(customer);
		return restTemplate.exchange("http://localhost:8080/customer", HttpMethod.PUT, httpEntity, Customer.class)
				.getBody();

		// restTemplate.put("http://localhost:8080/customer", customer);
	}
}
